import store from '@store/index'
import { debounce } from '../index'

function startLoading() {
  store.dispatch('loading/open')
}

function endLoading() {
  store.dispatch('loading/close')
}

// 请求个数
let needLoadingRequestCount = 0
// 展示loading，并计算请求个数
export function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}
// 失败或者完成请求，结束当前请求计数，为0时，防抖300毫秒，隐藏loading
export function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    debounce(tryCloseLoading, 300)()
  }
}
// 为0时，隐藏loading
const tryCloseLoading = () => {
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}
